import Validation from 'backbone-validation';
import Mn from 'backbone.marionette';

import FormBehavior from 'base/behaviors/FormBehavior.js';
import InputWidget from 'widgets/InputWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import Radio from 'backbone.radio';
import {
    hideLoader,
    showLoader
} from "../../tools";


const SupplierOrderLineFormView = Mn.View.extend({
    id: 'mainform-container',
    className: 'modal_overflow',
    behaviors: [FormBehavior],
    template: require('./templates/SupplierOrderLineFormView.mustache'),
    regions: {
        // 'date': '.date',
        'type_id': '.type_id',
        'description': '.description',
        'ht': '.ht',
        'tva': '.tva',
    },
    // Bubble up child view events
    //
    childViewTriggers: {
        'change': 'data:modified',
    },
    onBeforeSync: showLoader,
    onFormSubmitted: hideLoader,

    initialize() {
        this.channel = Radio.channel('config');
        this.type_options = this.getTypeOptions();
        var facade = Radio.channel('facade');
        this.listenTo(facade, 'bind:validation', this.bindValidation);
        this.listenTo(facade, 'unbind:validation', this.unbindValidation);
    },
    bindValidation() {
        Validation.bind(this);
    },
    unbindValidation() {
        Validation.unbind(this);
    },
    getTypeOptions() {
        return this.channel.request(
            'get:typeOptions',
            'purchase'
        );
    },
    onRender() {
        var view;
        view = new InputWidget({
            value: this.model.get('description'),
            title: 'Description',
            field_name: 'description'
        });
        this.showChildView('description', view);

        let ht_editable = this.channel.request('get:form_section', 'lines:ht')['edit'];
        view = new InputWidget({
            value: this.model.get('ht'),
            title: 'Montant HT',
            field_name: 'ht',
            addon: "€",
            required: true && ht_editable,
            editable: ht_editable,
        });
        this.showChildView('ht', view);
        let tva_editable = this.channel.request('get:form_section', 'lines:tva')['edit'];
        view = new InputWidget({
            value: this.model.get('tva'),
            title: 'Montant TVA',
            field_name: 'tva',
            addon: "€",
            required: true && tva_editable,
            editable: tva_editable
        });
        this.showChildView('tva', view);

        view = new SelectWidget({
            value: this.model.get('type_id'),
            title: 'Type de dépense',
            field_name: 'type_id',
            options: this.type_options,
            id_key: 'id',
        });

        this.showChildView('type_id', view);
    },
    templateContext: function () {
        return {
            title: this.getOption('title'),
            add: this.getOption('add'),
        };
    }
});
export default SupplierOrderLineFormView;